<template>
  <header class="navbar">
    <div class="navbar-container">
      <div class="logo" @click="router.push('/')">
        <div class="logo-icon">
          <el-icon><Reading /></el-icon>
        </div>
        <div class="logo-text">
          <h1>DevHub</h1>
          <span>开发者社区</span>
        </div>
      </div>

      <div class="navbar-actions">
        <slot name="extra-actions"></slot>
        <template v-if="!isLoggedIn">
          <button class="btn-login" @click="handleLoginClick">
            <el-icon><User /></el-icon>
            登录
          </button>
        </template>
        <template v-else>
          <button class="btn-write" @click="goToCreate">
            <el-icon><EditPen /></el-icon>
            <span>写文章</span>
          </button>
          <el-dropdown trigger="click" @command="handleCommand" class="user-menu">
            <div class="user-avatar-wrapper">
              <el-avatar :size="40" :src="getUserAvatar(currentUser.username)">
                {{ currentUser.username?.charAt(0)?.toUpperCase() }}
              </el-avatar>
              <span class="username">{{ currentUser.username }}</span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="myBlogs">
                  <el-icon><Document /></el-icon>
                  我的博客
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </div>
    </div>
  </header>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  Reading,
  User,
  EditPen,
  Document,
  SwitchButton
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

const emit = defineEmits(['openLogin'])

// 使用 ref 来响应式地追踪登录状态
const loginStatus = ref(!!localStorage.getItem('token'))
const isLoggedIn = computed(() => loginStatus.value)

const currentUser = computed(() => {
  const user = localStorage.getItem('user')
  return user ? JSON.parse(user) : {}
})

const handleLoginClick = () => {
  // 触发父组件的登录对话框
  emit('openLogin')
}

const goToCreate = () => {
  router.push('/create')
}

const handleCommand = (command) => {
  if (command === 'logout') {
    handleLogout()
  } else if (command === 'myBlogs') {
    router.push('/my-blogs')
  }
}

const handleLogout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('user')
  localStorage.removeItem('tokenType')
  localStorage.removeItem('expiresIn')
  
  // 更新登录状态
  loginStatus.value = false
  
  // 触发自定义事件通知其他组件
  window.dispatchEvent(new CustomEvent('user-logout'))
  
  ElMessage.success('已退出登录')
  router.push('/')
}

const getUserAvatar = (username) => {
  if (!username) return ''
  return `https://api.dicebear.com/7.x/avataaars/svg?seed=${username}`
}

// 监听认证过期事件（401错误）
const handleAuthExpired = () => {
  loginStatus.value = false
}

// 监听用户登出事件
const handleUserLogout = () => {
  loginStatus.value = false
}

// 监听用户登录事件
const handleUserLogin = () => {
  loginStatus.value = true
}

onMounted(() => {
  // 添加事件监听
  window.addEventListener('auth-expired', handleAuthExpired)
  window.addEventListener('user-logout', handleUserLogout)
  window.addEventListener('user-login', handleUserLogin)
})

onUnmounted(() => {
  // 移除事件监听
  window.removeEventListener('auth-expired', handleAuthExpired)
  window.removeEventListener('user-logout', handleUserLogout)
  window.removeEventListener('user-login', handleUserLogin)
})
</script>

<style scoped>
/* 导航栏 */
.navbar {
  background: rgba(17, 24, 39, 0.95);
  border-bottom: 1px solid var(--border-normal);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.8);
  position: sticky;
  top: 0;
  z-index: 1000;
  backdrop-filter: blur(20px);
}

.navbar-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 32px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  transition: transform 0.2s;
}

.logo:hover {
  transform: translateY(-1px);
}

.logo-icon {
  width: 36px;
  height: 36px;
  background: var(--gradient-primary);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--bg-primary);
  font-size: 20px;
  box-shadow: var(--shadow-glow);
}

.logo-text h1 {
  font-size: 20px;
  font-weight: 800;
  margin: 0;
  background: var(--gradient-primary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  line-height: 1;
}

.logo-text span {
  font-size: 10px;
  color: var(--text-tertiary);
  font-weight: 500;
  display: block;
  margin-top: 2px;
}

.navbar-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.btn-login,
.btn-write {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-login {
  background: var(--bg-tertiary);
  color: var(--primary-start);
  border: 1.5px solid var(--primary-start);
}

.btn-login:hover {
  background: var(--primary-start);
  color: var(--bg-primary);
  transform: translateY(-2px);
  box-shadow: var(--shadow-glow);
}

.btn-write {
  background: var(--gradient-primary);
  color: var(--bg-primary);
  box-shadow: var(--shadow-glow);
}

.btn-write:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 212, 255, 0.5);
}

.user-avatar-wrapper {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  padding: 6px 12px 6px 6px;
  border-radius: 50px;
  transition: all 0.2s;
}

.user-avatar-wrapper:hover {
  background: var(--bg-hover);
}

.username {
  font-size: 13px;
  font-weight: 600;
  color: var(--text-primary);
}

/* 响应式 */
@media (max-width: 768px) {
  .navbar-container {
    padding: 0 16px;
  }

  .logo-text span {
    display: none;
  }

  .btn-write span {
    display: none;
  }

  .user-avatar-wrapper .username {
    display: none;
  }
}
</style>

